#! -*- coding: utf-8 -*-
import sys

import pymongo
from mongoengine import connect
import psycopg2
import psycopg2.extras

sys.path.insert(0, '../..')
import app.models as models  # 可以直接从这里取得各个model对象，比如Mtu, Supplier, Product等

__all__ = ['models', 'query', 'get_one2dict', 'get_one2list', 'get_one2one', 'oid2nid']

MONGODB_SETTINGS = {
    'host': '192.168.1.198',
    'port': 27017
}

PSQL_SETTINGS = {
    # 'dbname': 'venti',
    'dbname': 'venti_20150701',
    'user': 'venti',
    'host': '192.168.1.198',
    'password': ''
}

# PSQL_SETTINGS = {
#     'dbname': 'venti_20150701',
#     'user': 'venti',
#     'host': '122.11.48.82',
#     'password': 'ventiataws'
# }


def get_pgsql_cursor():
    conn = psycopg2.connect(**PSQL_SETTINGS)
    # cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)  # 返回的是dict
    cur = conn.cursor()
    return cur


def get_pymongo_db_vtc():
    conn = pymongo.Connection(**MONGODB_SETTINGS)
    return conn.vtc


vtc = get_pymongo_db_vtc()
connect('vtc', **MONGODB_SETTINGS)  # 只要connect之后，就可以用model来创建数据了


def query(tbl, cols):
    """处理查询, 可指定字段"""
    psql_cur = get_pgsql_cursor()
    if cols == 'all':
        _sql = "select * from %s" % tbl
    else:
        _sql = "select %s from %s" % (','.join(cols), tbl)
    psql_cur.execute(_sql)
    return psql_cur.fetchall()


def get_one2dict(tbl, cols=None, field=None):
    """处理OneToDict关系"""
    id2dict = {}
    for row in query(tbl, cols=cols):
        _obj = dict(zip(cols, row))
        id2dict[_obj[field]] = _obj
    return id2dict


def get_one2list(tbl, col1, col2):
    """处理OneToList关系"""
    mapper = {}
    for row in query(tbl, cols=[col1, col2]):
        mapper.setdefault(row[0], []).append(row[1])
    return mapper


def get_one2one(tbl, col1, col2):
    mapper = {}
    for row in query(tbl, cols=[col1, col2]):
        mapper[row[0]] = row[1]
    return mapper


class Oid2nid:
    """处理ID映射关系"""

    def __init__(self):
        self.cache = {}

    def __getitem__(self, tbl):
        if tbl in self.cache:
            return self.cache[tbl]
        obj = {d['oldid']: d['_id'] for d in vtc.psqlid2mongoid.find({"tbl": tbl})}
        self.cache[tbl] = obj
        return obj


oid2nid = Oid2nid()


def test():
    for row in query("vacation_supplier", 'all'):
        print row


if __name__ == "__main__":
    test()
